import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:mmkv/mmkv.dart';
import 'package:seedfour/app/routes/app_routes.dart';

import '../../../constants.dart';
import '../../../models/notice_v2_list_entity.dart';
import '../../../services/api_service.dart';
import '../../../services/common_service.dart';
import '../notice_edit/logic.dart';

class NoticeLogic extends GetxController
    with GetSingleTickerProviderStateMixin {
  final apiService = Get.find<ApiService>();
  final commonService = Get.find<CommonService>();

  final loadingTip = '加载中...';
  final noMoreTip = '没有更多了';

  var isLoading = true.obs;
  var isSearching = false.obs;
  var isSearched = false.obs;
  var bottomTips = ''.obs;
  var noticeList = <NoticeV2Data>[].obs;
  var quota = 0.obs;
  var action = 'pub'.obs;
  var currentStatus = 0.obs;
  var ownerUid = ''.obs;

  final scrollController = ScrollController();
  final searchController = TextEditingController();

  late TabController tabController;

  final mmkv = MMKV.defaultMMKV();

  final pageSize = 20;
  int _page = 1;

  @override
  void onInit() {
    super.onInit();

    tabController = TabController(length: noticeIndex.length, vsync: this);
    tabController.addListener(() {
      if (tabController.index.toDouble() == tabController.animation?.value) {
        action.value = noticeIndex.keys.elementAt(tabController.index);
        reload();
      }
    });

    scrollController.addListener(() {
      if (scrollController.position.pixels ==
          scrollController.position.maxScrollExtent) {
        _getNoticeList(action.value, currentStatus.value);
      }
    });

    ownerUid.value = commonService.getUser().uid ?? '***';

    reload();
  }

  // 创建案源
  void toCreateNotice() async {
    dynamic result = await Get.toNamed(RouteGet.noticeEdit,
        arguments: NoticeEditParams(isCreate: true));

    if (result != null && result == true) {
      reload();
    }
  }

  // 查看案源详情
  void toNoticeDetail(int index) {
    noticeList[index].isRead = true;
    noticeList.refresh();
    mmkv.encodeBool('$kKeyNoticeReadTag${noticeList[index].id}', true);
    Get.toNamed(RouteGet.noticeDetail, arguments: noticeList[index].id);
  }

  void onStatusChange(int status) {
    currentStatus.value = status;
    _page = 1;
    noticeList.clear();
    isLoading.value = true;
    _getNoticeList(action.value, currentStatus.value);
  }

  void onClickSearch() {
    isSearching.value = true;
    isSearched.value = false;
  }

  void onCancelSearch() {
    isSearching.value = false;
    isSearched.value = false;
    searchController.clear();
  }

  void searchNotice() {
    if (searchController.text.isEmpty) {
      Get.snackbar('提示', '请输入搜索关键字');
      return;
    }

    _page = 1;
    noticeList.clear();
    isLoading.value = true;
    _getNoticeList(action.value, currentStatus.value);
  }

  void reload() {
    _page = 1;
    noticeList.clear();
    isLoading.value = true;
    isSearched.value = false;
    isSearching.value = false;
    searchController.clear();
    _getNoticeList(action.value, currentStatus.value);
  }

  void _getNoticeList(String action, int status) {
    apiService
        .getNoticeList(
          _page,
          pageSize,
          commonService.getRole(),
          action,
          keyword: isSearching.value ? searchController.text : '',
          status: status,
        )
        .then((notice) => {
              isLoading.value = false,
              isSearched.value = true,
              _page++,
              if (notice != null)
                {
                  quota.value = notice.quota ?? 0,
                  for (int i = 0; i < (notice.data ?? []).length; i++)
                    {
                      notice.data![i].isRead = mmkv
                          .decodeBool('$kKeyNoticeReadTag${notice.data![i].id}')
                    },
                  noticeList.addAll(notice.data ?? []),
                  if (notice.data!.length < pageSize)
                    {bottomTips.value = noMoreTip}
                  else
                    {bottomTips.value = loadingTip}
                }
              else
                {bottomTips.value = noMoreTip}
            });
  }
}
